package sv.com.compassion.util;


import com.opensymphony.xwork2.ActionSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import sv.com.compassion.servicio.GenericoDAOImpl;

/**
 * Clase con métodos utilitarios, para realizar mantenimiento completo y reporte de cada entidad.
 * @author grupo de Tesis
 */
public class ComunAction extends ActionSupport{
    private Integer rows;
    private Integer page;
    private Integer total;
    private Integer record;
    private String sord;
    private String sidx;
    private boolean loadonce;
    private String searchOper;
    private String searchString;
    private String searchField;
    private List<?> gridModel;
    private String id;
    private String _search;
    private String oper;
    private String nd;
    
/**
 * Busca el método que se ejecutara
 */
    public void buscarMetodo(Object o){
        oper = getRequest().getParameter("oper");
        if(getOper() != null){
            if(getOper().equals("add"))
                agregarEntidad(o);
            else{
                if(getOper().equals("edit"))
                    editarEntidad(o);
                else
                    if(getOper().equals("del"))
                        borrarEntidad(o);
                    else
                        if(getOper().equals("xls"))
                            reporteXls(); 
            }
        }else
            alimentarGrid();
    }
    /**
     * @param o de tipo Object, para agregar una entidad.
     */
    public void agregarEntidad(Object o){
        GenericoDAOImpl GenericoDAOImpl =   new GenericoDAOImpl();
        GenericoDAOImpl.save(o);
        
    }
    /**
     * @param o de tipo Object para Editar una entidad
     */
    public void editarEntidad(Object o){
    }
  /*  public void guardarAsistencia(Object o){
    }*/
    /**
     * @param o de tipo Object para borrar un registro de una entidad.
     */
    public void borrarEntidad(Object o){
    }
    /**
     * Mostrar los registros.
     */
    public void alimentarGrid(){

    }
    
    public void reporteXls() {}
/**
     * Devuelve el request.
     * @return Request
     */
    public HttpServletRequest getRequest(){
        return ServletActionContext.getRequest();
    }
    /**
     * Devuelve el response.
     * @return Response
     */
    public HttpServletResponse getResponse(){
        return ServletActionContext.getResponse();
    }
    /**
     * @param response
     * @param jo 
     * Envia la estructura de un Jason a la JSP.
     */
    public void enviarJsonNavegador(HttpServletResponse response, JSONObject jo){
        try {
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(jo);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            Logger.getLogger(ComunAction.class.getName()).log(Level.SEVERE, null, e);
        }

    }
/**
* @param response
* @param jao 
* Envia la estructura de un Jason a la JSP.
*/
    public void enviarJsonNavegador(HttpServletResponse response, JSONArray jao){
                try {
                            response.setCharacterEncoding("utf-8");
                            response.getWriter().println(jao);
                            response.getWriter().flush();
                            response.getWriter().close();
                } catch (IOException e) {
                    Logger.getLogger(ComunAction.class.getName()).log(Level.SEVERE, null, e);
                }

    }

/**
* @param mensaje
* @param response 
* Enviar mensaje estático a la JSP.
*/
   public static void enviarMensajeStatic(String mensaje, HttpServletResponse response){
                String valores[]=mensaje.split(Constantes.SEPARADOR);                
                List<Combo> listC = new ArrayList<Combo>();
                Combo c = new Combo();
                JSONArray jo = null;
                if("exito".equals(valores[0])){
                    c.setValor("exito");
                    c.setDescripcion(valores[1]);
                    listC.add(c);
                    jo = JSONArray.fromObject (listC);
                }else{
                    if("aviso".equals(valores[0])){
                        c.setValor("aviso");
                        c.setDescripcion(valores[1]);
                        listC.add(c);
                        jo = JSONArray.fromObject (listC);
                    }else{
                        c.setValor("error");
                        c.setDescripcion(valores[1]);
                        listC.add(c);
                        jo = JSONArray.fromObject (listC);
                    }
                }
                enviarJsonNavegadorStatic(response, jo);
    }
//---
   /**
    * @param response
    * @param jo 
    * Envia la estructura de un Jason a la JSP.
    */
    public static void enviarJsonNavegadorStatic(HttpServletResponse response,JSONArray jo){
                try {
                    response.setCharacterEncoding("utf-8");
                    response.getWriter().println(jo);
                    response.getWriter().flush();
                    response.getWriter().close();
                } catch (IOException e) {
                    Logger.getLogger(ComunAction.class.getName()).log(Level.SEVERE, null, e);
                }

    }
   /**
    * @param response
    * @param jo 
    * Envia la estructura de un Jason a la JSP.
    */
    public static void enviarArchivoNavegador(byte []bytes,String nombreArchivo,String formato) throws IOException{
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setHeader("Cache-Control", "private");
        response.setHeader("Pragma", "Cache");
        response.setContentType("application/"+formato.toLowerCase());
        response.setHeader("content-Disposition", "attachment;filename="+nombreArchivo+"."+formato.toLowerCase());
        response.setContentLength(bytes.length);
        ServletOutputStream ouputStream = response.getOutputStream();
        ouputStream.write(bytes);
        ouputStream.flush();
        ouputStream.close();
    }

 public Integer getRows()
  {
    return rows;
  }

  /**
   * @param rows
   *          how many rows we want to have into the grid
   */
  public void setRows(Integer rows)
  {
    this.rows = rows;
  }

  /**
   * @return current page of the query
   */
  public Integer getPage()
  {
    return page;
  }

  /**
   * @param page
   *          current page of the query
   */
  public void setPage(Integer page)
  {
    this.page = page;
  }

  /**
   * @return total pages for the query
   */
  public Integer getTotal()
  {
    return total;
  }

  /**
   * @param total
   *          total pages for the query
   */
  public void setTotal(Integer total)
  {
    this.total = total;
  }

  /**
   * @return total number of records for the query. e.g. select count(*) from
   *         table
   */
  public Integer getRecord()
  {
    return record;
  }

  /**
   * @param record
   *          total number of records for the query. e.g. select count(*) from
   *          table
   */
  public void setRecord(Integer record)
  {

    this.record = record;

    if (this.record > 0 && this.rows > 0)
    {
      this.total = (int) Math.ceil((double) this.record / (double) this.rows);
    }
    else
    {
      this.total = 0;
    }
  }

  /**
   * @return an collection that contains the actual data
   */
  public List<?> getGridModel()
  {
    return gridModel;
  }

  /**
   * @param gridModel
   *          an collection that contains the actual data
   */
  public void setGridModel(List<?> gridModel)
  {
    this.gridModel = gridModel;
  }

  /**
   * @return sorting order
   */
  public String getSord()
  {
    return sord;
  }

  /**
   * @param sord
   *          sorting order
   */
  public void setSord(String sord)
  {
    this.sord = sord;
  }

  /**
   * @return get index row - i.e. user click to sort.
   */
  public String getSidx()
  {
    return sidx;
  }

  /**
   * @param sidx
   *          get index row - i.e. user click to sort.
   */
  public void setSidx(String sidx)
  {
    this.sidx = sidx;
  }

  public void setSearchField(String searchField)
  {
    this.searchField = searchField;
  }

  public void setSearchString(String searchString)
  {
    this.searchString = searchString;
  }

  public void setLoadonce(boolean loadonce)
  {
    this.loadonce = loadonce;
  }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getSearchOper() {
        return searchOper;
    }

    public void setSearchOper(String searchOper) {
        this.searchOper = searchOper;
    }

    public String getSearch() {
        return getRequest().getParameter("_search");
    }

    public void setSearch(String _search) {
        this._search = _search;
    }

    public String getOper() {
        return oper;
    }

    public void setOper(String oper) {
        this.oper = oper;
    }
/*    public String getSearch() {
        return _search;
    }

    public void setSearch(String _search) {
        this._search = _search;
    }*/

    public String getNd() {
        return nd;
    }

    public void setNd(String nd) {
        this.nd = nd;
    }
}

